<?php
namespace app\controller;

use think\App;
use think\captcha\facade\Captcha;
use think\facade\Db;
use think\Request;
use think\facade\View;
use app\validate\CheckLogin;
use think\exception\ValidateException;
use think\facade\Session;
use think\Image;

/**
 *登录
 */
class Login
{


    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;


    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {
        header("Content-type: text/html; charset=utf-8");
        if(!$this->validates($this->request->server('PHP_AUTH_USER'), $this->request->server('PHP_AUTH_PW'))) {
            http_response_code(401);
            header('WWW-Authenticate:Basic realm="My website"'); //对话框显示 http://127.0.0.3 请求用户名和密码。信息为：My website
            echo '需要用户名和密码才能继续访问'; //取消时浏览器输出
            exit;
        }
    }


    protected function validates($user, $pass) {
        $users = ['loreal'=>'1234567890', 'admin'=>'admin'];
        if(isset($users[$user]) && $users[$user] === $pass) {
            return true;
        } else {
            return false;
        }
    }

    public function metadata()
    {

        try {
            $settings = new \OneLogin\Saml2\Settings(null, true);

            $metadata = $settings->getSPMetadata();
            $errors = $settings->validateMetadata($metadata);
            if (empty($errors)) {
                header('Content-Type: text/xml');
                echo $metadata;
            } else {
                throw new \OneLogin\Saml2\Error(
                    'Invalid SP metadata: '.implode(', ', $errors),
                    \OneLogin\Saml2\Error::METADATA_SP_INVALID
                );
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    public function index(Request $request)
    {
        $auth = new \OneLogin\Saml2\Auth();
        $auth->login();
    }


    // 备用登录方式
    public function spare()
    {
        return View::fetch();
    }


    // 验证码
    public function verify()
    {
        return Captcha::create();
    }

    //备用登录方式--登录操作
    public function doLogin(Request $request)
    {

        $post = $request->post();

        // 验证
        try {

            validate(CheckLogin::class)->check($post);

        } catch (ValidateException $e) {

            return json(['code' => 500, 'data' => '', 'msg' => $e->getError()]);
        }


        try {

            $result = Db::name('admin_user')
                ->where('email', '=', trim($post['email']))
                ->where('givenname', '=', trim($post['givenname']))
                ->where('surname', '=', trim($post['surname']))
                ->field('givenname, surname, role_id, id, status, email')
                ->find();

            if ($result) {
                if ($result['status'] != 1) {
                    return json(['code' => 500, 'data' => '', 'msg' => '账号已锁定, 请联系管理人员！']);
                } else {

                    //更新管理员状态
                    $param = [
                        'last_login_ip' => request()->ip(),
                        'last_login_time' => time()
                    ];

                    Db::name('admin_user')->where('id', $result['id'])->update($param);
                    session('admin_auth', $result);
                    session('aad', $result);
                    return json(['code' => 200, 'data' => '', 'msg' => '登录成功']);
                }
            } else {
                return json(['code' => 500, 'data' => '', 'msg' => '账户不存在或密码错误！']);
            }

        } catch (\Exception $ex) {
            return json(['code' => 500, 'data' => '', 'msg' => $ex->getMessage()]);
        }
    }

    public function logout()
    {
        session('admin_auth', null);
        session('aad', null);
    }


    public function error()
    {
        return View::fetch();
    }


    public function locking()
    {
        return View::fetch();
    }
}